<?php
/**
 * ToolsController.php
 *
 * @author: cnx7 <zysafe@live.cn> 2021-03-12
 */

namespace app\commands;

use common\domain\helper\Tools;
use yii\console\Controller;
use yii\console\ExitCode;

class ToolsController extends Controller
{

    /**
     * 自动创建数据库Model类
     * @param string $table_name 表名
     * @return int
     * @throws \yii\base\NotSupportedException
     */
    public function actionCreateModel($table_name = ''): int
    {
        $schema = \Yii::$app->db->getSchema();
        $tables = $schema->getTableNames();
        $date = date('Y-m-d');

        foreach ($tables as $table) {
            // 迁移库跳过
            if ($table == 'migration' || $table == 'migrations') continue;
            // 如果指定表名则跳过其他
            if ($table_name && $table !== $table_name) continue;

            // 表名转换大驼峰
            $class = ucfirst(Tools::camelize($table));

            echo '-----------------' . PHP_EOL;
            echo '正在处理表:' . $table . PHP_EOL;

            // 字段名数组
            $columns = $schema->getTableSchema($table)->getColumnNames();

            $property = '';
            foreach ($columns as $column) {
                // 获取字段属性
                $column_info = $schema->getTableSchema($table)->getColumn($column);
                // 拼接注释行
                $property .= <<<PROPERTY
 * @property {$column_info->phpType} {$column_info->name} {$column_info->comment}

PROPERTY;
            }

            $file_str = <<<STR
<?php
/**
 * {$class}.php
 *
 * @author: cnx7 <zysafe@live.cn> {$date}
 */

namespace common\models\base;

use \yii\db\ActiveRecord;

/**
 * Class {$class}
 * @package common\models
 *
{$property} */
class {$class} extends ActiveRecord
{

    public static function tableName()
    {
        return '{$table}';
    }

}

STR;
            // 判断文件是否存在
            $file = ROOT_PATH . '/common/models/' . $class . '.php';

            if (is_file($file)) {
                echo '存在文件' . $class . '，是否覆盖？(输入y或Y确认覆盖，其他输入则跳过)' . PHP_EOL;

                $fp = fopen('/dev/stdin', 'r');
                $input = fgets($fp, 2);
                fclose($fp);
                $input = rtrim($input);

                if ($input !== 'y' && $input !== 'Y') {
                    echo '已跳过' . PHP_EOL;
                    continue;
                }
            }
            // 写入文件
            file_put_contents($file, $file_str);

        }

        return ExitCode::OK;
    }
}
